//
//  PayView.m
//  夺宝吧
//
//  Created by xiaocai on 15/6/23.
//  Copyright (c) 2015年 FangYuan. All rights reserved.
//

#import "PayView.h"
#import "PayVC.h"
#import "WYShopCarModel.h"
#import "ShoppingCarVC.h"

@interface PayView ()

@end
@implementation PayView

- (void)awakeFromNib
{
    
    self.PayBtn.layer.masksToBounds = YES;
    self.PayBtn.layer.cornerRadius = 2;
    self.PayBtn.backgroundColor = QBB_RED_COLOR;
    [self changeColorWithCount:2 andMoney:0];
}
//去结算按钮
- (IBAction)payBtnOnClick:(id)sender {
    
    if([WYPublic ifUserHaveLogin]){
        //生成订单
        [self requestForOrder];
    }else{
    }
}
//请求订单
- (void)requestForOrder
{
//    [WYPublic addZheZhaoToWindowWithTitle:nil];
    [WYPublic addHudToWindow];
    self.PayBtn.enabled = NO;
    
    NSLog(@"%@",self.data);
//    _data = [[NSMutableArray alloc]initWithArray:[[WYDataBase sharedDataBase]getAllpdcInCar]];
    

    if (self.data.count > 0) {
        NSString *jsonStr = @"[";
        for (WYShopCarModel *model in _data) {
            if (jsonStr.length <= 1) {
                jsonStr = [jsonStr stringByAppendingString:[NSString stringWithFormat:@"{\"id\": %@, \"gonumber\": %d}",model.car_id,model.count]];
            }else{
               jsonStr = [jsonStr stringByAppendingString:[NSString stringWithFormat:@",{\"id\": %@, \"gonumber\": %d}",model.car_id,model.count]];
            }
        }
        
        jsonStr = [jsonStr stringByAppendingString:@"]"];
        NSDictionary *params = nil;
        if ([UserInfo getUserID]!= nil && [UserInfo getUserToken]!= nil && [UserInfo getRefreshToken] !=nil) {
            params = @{@"cart_info":jsonStr,@"uid":[UserInfo getUserID],@"token":[UserInfo getUserToken],@"refresh_token":[UserInfo getRefreshToken]};
        }else{
            UIAlertView *alt = [[UIAlertView alloc]initWithTitle:@"温馨提示：" message:@"您尚未登录！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alt show];
            return;
        }
        NSLog(@"%@",params);
        [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,MAKE_ORDER_URL] Parameters:params successBlock:^(NSDictionary *dic) {
            
            [WYPublic removeHudToWindow];
            self.PayBtn.enabled = YES;
            NSNumber *ret = dic[@"ret"];
            if (ret.intValue == 0) {
                //先刷新用户信息
                [UserInfo updateUserInfoWithDic:dic[@"data"][@"user"]];
                //然后获取有效订单列表
                PayVC *payVC = [[PayVC alloc]init];
                payVC.orderId = dic[@"data"][@"pay_order"][@"id"];
                NSString *price = dic[@"data"][@"pay_order"][@"pay_moneytotal"];
                payVC.allPrice = [price integerValue];
                payVC.paycode = dic[@"data"][@"pay_order"][@"pay_code"];
                
                //默认4个支付都存在
                payVC.zfbflag = 1;
                payVC.jdflag = 1;
                payVC.iapppayflag = 1;
                payVC.iapppayFlagAlipay = 1;
                
                //支付宝是否可用
                NSNumber *zn = dic[@"data"][@"valid_pays"][@"alipay_mobile"][@"available"];
                if (zn == nil) {
                    payVC.zfbflag = 0;
                }else{
                    payVC.zfbflag = [zn intValue];
                }
                //京东支付是否可用
                NSNumber *jn = dic[@"data"][@"valid_pays"][@"pingpp"][@"available"];
                if (jn == nil) {
                    payVC.jdflag = 0;
                }else{
                    payVC.jdflag = [jn intValue];
                }
                //update by weienjie 20150918
                
                //Iapppay中的微信支付是否可用
                NSNumber *iappay = dic[@"data"][@"valid_pays"][@"iapppay"][@"available"];
                if (iappay == nil) {
                    payVC.iapppayflag = 0;
                }else{
                    payVC.iapppayflag = [iappay intValue];
                }
                //Iapppay支付宝是否可用
                NSNumber *iappayAlipay = dic[@"data"][@"valid_pays"][@"iapppay_alipay"][@"available"];
                if (iappayAlipay == nil){
                    payVC.iapppayFlagAlipay = 0;
                }
                else{
                    payVC.iapppayFlagAlipay = [iappayAlipay intValue];
                }
//                payVC.iapppayFlagAlipay = 1;
//                payVC.zfbflag = 0;
//                payVC.iapppayFlagAlipay = 0;
//                payVC.jdflag = 0;
                //要支付的商品
                
                //向payVC中传递支付模型
                [self setInitChongZhiInfoIntoChongZhiController:payVC dict:dic];
                
                NSArray *pdcs = dic[@"data"][@"pay_order"][@"record_rows"];
                if (pdcs.count > 0) {
                    for (NSDictionary *pdc in pdcs) {
                        WYShopCarModel *model = [[WYShopCarModel alloc]init];
                        model.imgPath = pdc[@"thumb_url"];
                        model.car_id = pdc[@"id"];
                        model.name = pdc[@"shopname"];
                        model.qishu = pdc[@"shopqishu"];
                        NSString *count = pdc[@"gonumber"];
                        model.count = [count intValue];
                        [payVC.data addObject:model];
                    } 
                    //跳往支付界面
                    [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:payVC animated:YES];
                }
            }
            else if(ret.intValue>2000 && ret.intValue < 3000){
                //用户过期，强制重新登录 先删除用户信息
                [UserInfo deleteUserInfo];
                //登录
                [WYPublic ifUserHaveLogin];
                [[WYMainTabBarVC shareMainTaBarVC]changeSelectedWithIndex:2];
            }
            else{
                [WYPublic showMessageWithTitle:@"订单提交失败：" Msg:dic[@"msg"]];
                [[ShoppingCarVC shareShoppingCarVC] viewWillAppear:YES];
            }
        } failedBlock:^{
            NSLog(@"failedBlock");
            
            [WYPublic removeZheZhaoToWindow];
            self.PayBtn.enabled = YES;

        } needLog:NO];
    }
    else{
        [WYPublic removeHudToWindow];
        self.PayBtn.enabled = YES;

    }
}
//此处的dic是原生的dic 需要手动将其他的数据剥离s
- (void)setInitChongZhiInfoIntoChongZhiController:(PayVC*)payVC dict:(NSDictionary*)dic{
    //支付宝支付模型
    PayInfoModel *zfbPayModel = [[PayInfoModel alloc]init];
    NSDictionary *dict1 = dic[@"data"][@"valid_pays"][@"alipay_mobile"][@"pay_info"];
    if (![dict1 isKindOfClass:[NSNull class]]){
        [zfbPayModel setValuesForKeysWithDictionary:dict1];
    }
    //爱贝微信支付模型
    PayInfoModel *iapppayWXPayModel = [[PayInfoModel alloc]init];
    NSDictionary *dict2 = dic[@"data"][@"valid_pays"][@"iapppay"][@"pay_info"];
    if (![dict2 isKindOfClass:[NSNull class]]){
        [iapppayWXPayModel setValuesForKeysWithDictionary:dict2];
    }
    //爱贝微信支付模型
    PayInfoModel *iapppayzfbPayModel = [[PayInfoModel alloc]init];
    NSDictionary *dict3 = dic[@"data"][@"valid_pays"][@"iapppay_alipay"][@"pay_info"];
    if (![dict3 isKindOfClass:[NSNull class]]){
        [iapppayzfbPayModel setValuesForKeysWithDictionary:dict3];
    }
    //pingpp京东支付模型
    PayInfoModel *pingppJDPayModel = [[PayInfoModel alloc]init];
    NSDictionary *dict4 = dic[@"data"][@"valid_pays"][@"pingpp"][@"pay_info"];
    if (![dict4 isKindOfClass:[NSNull class]]){
        [pingppJDPayModel setValuesForKeysWithDictionary:dict4];
    }
    
    payVC.zfbModel = zfbPayModel;
    payVC.iapppayWXModel = iapppayWXPayModel;
    payVC.iapppayzfbModel = iapppayzfbPayModel;
    payVC.pingppJDModel = pingppJDPayModel;
    
}

- (void)changeColorWithCount:(NSInteger)count andMoney:(NSInteger)money
{
    NSString *str1 = [NSString stringWithFormat:@"共参与%ld件奖品",(unsigned long)count];
    NSString *str2 = [NSString stringWithFormat:@"共参与%ld件奖品，总计%ld夺宝币",(unsigned long)count,(unsigned long)money];
    NSString *str3 = [NSString stringWithFormat:@"总计%ld夺宝币",(unsigned long)money];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:str2];
    [str addAttribute:NSForegroundColorAttributeName value:QBB_RED_COLOR range:NSMakeRange(str1.length+1,str3.length)];
    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:14.0] range:NSMakeRange(0, str2.length)];
    self.payLab.attributedText = str;
}

//修改购物车中显示的总数量
-(void)setData:(NSArray *)data{
    //count是计算的总购买期数
    int count = 0;
    //
    _data = data;
    for (WYShopCarModel *model in data){
        count += model.count;
    }
    self.payLab.text = [NSString stringWithFormat:@"共参与%lu件奖品，总计%d夺宝币",(unsigned long)data.count,count];
}
@end
